<template>
  <div>
    <!-- 页面标题栏 -->
    <div class="page-header" style="margin-bottom: 20px;">
      <h2 style="color: #409EFF; font-size: 20px; margin-bottom: 0;">商品管理</h2>
    </div>
    
    <!-- 搜索区域 -->
    <div class="flex items-center mb-4">
      <el-input 
        v-model="searchProductName" 
        placeholder="请输入商品名称" 
        @keyup.enter="fetchProducts" 
        class="flex-1 mr-4 custom-input"
        size="default"
        :prefix-icon="Search"
      />
      <el-input 
        v-model="searchCategoryName" 
        placeholder="请输入商品种类" 
        @keyup.enter="fetchProducts" 
        class="flex-1 mr-4 custom-input"
        size="default"
        :prefix-icon="Search"
      />
      <el-button 
        type="primary" 
        @click="addProduct"
        :icon="Plus"
      >
        添加商品
      </el-button>
    </div>
    
    <!-- 商品表格 -->
    <el-card shadow="hover" class="mb-6" style="border-radius: 4px;">
      <el-table 
        :data="products" 
        stripe 
        border="false"
        style="width: 100%"
        v-loading="loading"
        element-loading-text="加载中..."
        header-row-class-name="table-header"
        class="custom-table"
      >
        <el-table-column prop="categoryName" label="商品种类" align="center" min-width="120" />
        <el-table-column prop="productName" label="商品名称" align="center" min-width="150" />
        <el-table-column prop="price" label="价格" align="center" min-width="100" />
        <el-table-column prop="stock" label="库存" align="center" min-width="100" />
        <el-table-column prop="dict" label="计量单位" align="center" min-width="120" />
        <el-table-column label="商品图片" min-width="120">
          <template #default="scope">
            <el-image 
              v-if="scope.row.imageUrl" 
              :src="scope.row.imageUrl" 
              fit="cover"
              style="width: 80px; height: 80px;"
              preview-teleported
              :preview-src-list="[scope.row.imageUrl]"
            >
              <template #error>
                <div style="display: flex; align-items: center; justify-content: center; width: 80px; height: 80px; background-color: #f5f7fa;">
                  <el-icon><PictureFilled /></el-icon>
                </div>
              </template>
            </el-image>
            <div v-else style="display: flex; align-items: center; justify-content: center; width: 80px; height: 80px; background-color: #f5f7fa;">
              <el-icon><PictureFilled /></el-icon>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" min-width="120" fixed="right">
          <template #default="scope">
            <div class="flex justify-center">
              <el-button 
                type="primary" 
                size="small" 
                @click="editProduct(scope.row)"
                :icon="Edit"
                class="mr-2"
              >
                修改
              </el-button>
              <el-button 
                type="danger" 
                size="small" 
                @click="confirmDelete(scope.row.productId)"
                :icon="Delete"
              >
                删除
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    
    <!-- 分页组件 -->
    <div class="pagination-container">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[10, 20, 30]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        background
      />
    </div>
    
    <!-- 添加商品对话框 -->
    <el-dialog 
      v-model="dialogVisible" 
      title="添加商品"
      width="600px"
      center
    >
      <el-form ref="productFormRef" :model="productForm" label-width="100px" :rules="rules">
        <el-form-item label="商品名称" prop="productName">
          <el-input v-model="productForm.productName" placeholder="请输入商品名称" />
        </el-form-item>
        <el-form-item label="商品种类" prop="categoryId">
          <el-select
              v-model="productForm.categoryId"
              placeholder="请选择商品种类"
              @focus="fetchCategoryList"
          >
            <el-option
                v-for="category in categoryList"
                :key="category.categoryId"
                :label="category.categoryName"
                :value="category.categoryId"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="价格" prop="price">
          <el-input v-model="productForm.price" type="number" placeholder="请输入价格" />
        </el-form-item>
        <el-form-item label="库存" prop="stock">
          <el-input v-model="productForm.stock" type="number" placeholder="请输入库存" />
        </el-form-item>
        <el-form-item label="计量单位" prop="dict">
          <el-select
              v-model="productForm.dict"
              placeholder="请选择计量单位"
              @focus="fetchDictList"
          >
            <el-option
                v-for="dict in dictList"
                :key="dict.dictId"
                :label="dict.dictName"
                :value="dict.dictName"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="商品图片">
          <el-upload
              class="upload-demo"
              :http-request="customUploadRequest"
              :show-file-list="false"
              :on-success="handleUploadSuccess"
              :on-error="handleUploadError"
              :before-upload="beforeUpload"
            drag
          >
            <el-image v-if="productForm.imageUrl" :src="productForm.imageUrl" alt="商品图片" style="width: 200px; height: 200px; object-fit: cover;" />
            <div v-else class="upload-box">
              <el-icon class="upload-icon"><Plus /></el-icon>
              <div class="upload-text">点击或拖拽文件到此处上传</div>
              <div class="upload-hint">支持 JPG/PNG 格式，文件大小不超过 5MB</div>
            </div>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="cancelAdd">取消</el-button>
          <el-button type="primary" @click="saveProduct">确定</el-button>
        </span>
      </template>
    </el-dialog>
    
    <!-- 修改商品对话框 -->
    <el-dialog 
      v-model="dialogVisible1" 
      title="修改商品"
      width="600px"
      center
    >
      <el-form ref="productFormRef" :model="productForm" label-width="100px" :rules="rules">
        <el-form-item label="商品名称" prop="productName">
          <el-input v-model="productForm.productName" placeholder="请输入商品名称" />
        </el-form-item>
        <el-form-item label="商品种类" prop="categoryId">
          <el-select
              v-model="productForm.categoryId"
              @change="handleCategoryChange"
              @focus="fetchCategoryList"
            placeholder="请选择商品种类"
          >
            <el-option
                v-for="category in categoryList"
                :key="category.categoryId"
                :label="category.categoryName"
                :value="category.categoryId"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="价格" prop="price">
          <el-input v-model="productForm.price" type="number" placeholder="请输入价格" />
        </el-form-item>
        <el-form-item label="库存" prop="stock">
          <el-input v-model="productForm.stock" type="number" placeholder="请输入库存" />
        </el-form-item>
        <el-form-item label="计量单位" prop="dict">
          <el-select
              v-model="productForm.dict"
              placeholder="请选择计量单位"
              @focus="fetchDictList"
          >
            <el-option
                v-for="dict in dictList"
                :key="dict.dictId"
                :label="dict.dictName"
                :value="dict.dictName"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="商品图片">
          <el-upload
              class="upload-demo"
              :http-request="customUploadRequest"
              :show-file-list="false"
              :on-success="handleUploadSuccess"
              :on-error="handleUploadError"
              :before-upload="beforeUpload"
            drag
          >
            <el-image v-if="productForm.imageUrl" :src="productForm.imageUrl" alt="商品图片" style="width: 200px; height: 200px; object-fit: cover;" />
            <div v-else class="upload-box">
              <el-icon class="upload-icon"><Plus /></el-icon>
              <div class="upload-text">点击或拖拽文件到此处上传</div>
              <div class="upload-hint">支持 JPG/PNG 格式，文件大小不超过 2MB</div>
            </div>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="cancelAdd">取消</el-button>
          <el-button type="primary" @click="saveProduct">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue';
import axiosInstance from '../axiosInstance';
import { Plus, Search, Edit, Delete, PictureFilled } from '@element-plus/icons-vue';
import { ElMessageBox } from 'element-plus';

const searchProductName = ref('');
const searchCategoryName = ref('');
const products = ref([]);
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);
const dialogVisible = ref(false);
const dialogVisible1 = ref(false);
const loading = ref(false);
const productForm = ref({
  productName: '',
  categoryId: '',
  price: '',
  stock: '',
  imageUrl: '',
  dict: ''
});
const productFormRef = ref(null);
const uploadUrl = '/upload/image';
const tempImageUrl = ref('');
const downloadUrl = ref('');
const categoryList = ref([]);
const dictList = ref([]);
const isCategoryListFetched = ref(false);
const isCategoryListFetchFailed = ref(false); // 新增标记，记录请求是否失败
const isDictListFetched = ref(false);
const isDictListFetchFailed = ref(false);

// 表单验证规则
const rules = reactive({
  productName: [
    { required: true, message: '请输入商品名称', trigger: 'blur' },
    { min: 1, max: 50, message: '商品名称长度在 1 到 50 个字符', trigger: 'blur' }
  ],
  categoryId: [
    { required: true, message: '请选择商品种类', trigger: 'change' }
  ],
  price: [
    { required: true, message: '请输入价格', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        const numValue = Number(value);
        if (isNaN(numValue) || numValue <= 0) {
          callback(new Error('价格必须大于0'));
        } else {
          callback();
        }
      },
      trigger: 'blur'
    }
  ],
  stock: [
    { required: true, message: '请输入库存', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        const numValue = Number(value);
        if (isNaN(numValue) || numValue < 0) {
          callback(new Error('库存必须大于等于0'));
        } else {
          callback();
        }
      },
      trigger: 'blur'
    }
  ],
  dict: [
    { required: true, message: '请选择计量单位', trigger: 'change' }
  ]
});

const fetchProducts = async () => {
  loading.value = true;
  try {
    const requestData = {
      productName: searchProductName.value,
      categoryName: searchCategoryName.value,
      page: currentPage.value,
      pageSize: pageSize.value
    };
    const response = await axiosInstance.post('/product/list', requestData);
    if (response.data.code === '200') {
      products.value = response.data.data.listData;
      total.value = Number(response.data.data.total);
    } else {
      ElMessageBox.alert(response.data.message, '提示', {
        confirmButtonText: '确定',
        type: 'error',
        customClass: 'center-message-box'
      });
    }
  } catch (error) {
    if(error.response){
      const { status } = error.response;
      if (status === 401) {
        return;
      }
    }
    console.error(error);
    ElMessageBox.alert('获取商品列表失败，请稍后重试', '提示', {
      confirmButtonText: '确定',
      type: 'error',
      customClass: 'center-message-box'
    });
  } finally {
    loading.value = false;
  }
};

const fetchCategoryList = async () => {
  if (isCategoryListFetched.value || isCategoryListFetchFailed.value) return;

  try {
    const response = await axiosInstance.get('/category/allList');
    if (response.data.code === '200') {
      categoryList.value = response.data.data;
      isCategoryListFetched.value = true;
    } else {
      ElMessageBox.alert(response.data.message, '提示', {
        confirmButtonText: '确定',
        type: 'error',
        customClass: 'center-message-box'
      });
      isCategoryListFetchFailed.value = true; // 标记请求失败
    }
  } catch (error) {
    console.error(error);
    ElMessageBox.alert('获取商品种类列表失败，请稍后重试', '提示', {
      confirmButtonText: '确定',
      type: 'error',
      customClass: 'center-message-box'
    });
    isCategoryListFetchFailed.value = true; // 标记请求失败
  }
};

const fetchDictList = async () => {
  if (isDictListFetched.value || isDictListFetchFailed.value) return;

  try {
    const response = await axiosInstance.get('/dict/allList');
    if (response.data.code === '200') {
      dictList.value = response.data.data;
      isDictListFetched.value = true;
    } else {
      ElMessageBox.alert(response.data.message, '提示', {
        confirmButtonText: '确定',
        type: 'error',
        customClass: 'center-message-box'
      });
      isDictListFetchFailed.value = true; // 标记请求失败
    }
  } catch (error) {
    console.error(error);
    ElMessageBox.alert('获取计量单位列表失败，请稍后重试', '提示', {
      confirmButtonText: '确定',
      type: 'error',
      customClass: 'center-message-box'
    });
    isDictListFetchFailed.value = true; // 标记请求失败
  }
};

const addProduct = () => {
  dialogVisible.value = true;
  productForm.value = {
    productName: '',
    categoryId: '',
    price: '',
    stock: '',
    imageUrl: '',
    dict: ''
  };
  tempImageUrl.value = '';
  isCategoryListFetched.value = false;
  isCategoryListFetchFailed.value = false; // 重置标记，下次打开对话框可重新尝试请求
  isDictListFetched.value = false;
  isDictListFetchFailed.value = false;
};

const customUploadRequest = (params) => {
  const formData = new FormData();
  formData.append('file', params.file);

  axiosInstance.post(uploadUrl, formData, {
    headers: {
      'Content-Type': 'multipart/form-data'
    }
  })
      .then((response) => {
        params.onSuccess(response.data);
      })
      .catch((error) => {
        params.onError(error);
      });
};

const handleUploadSuccess = (response) => {
  if (response.code === '200') {
    tempImageUrl.value = response.data.imageUrl;
    productForm.value.imageUrl = response.data.imageUrl;
    // 发起请求获取二进制图片数据
    axiosInstance.get(`/upload/download?imageUrl=${response.data.imageUrl}`, {
      responseType: 'arraybuffer' // 设置响应类型为 arraybuffer，以获取二进制数据
    })
        .then((imageResponse) => {
          // 将二进制数据转换为 Blob 对象
          const blob = new Blob([imageResponse.data], { type: imageResponse.headers['content-type'] });
          // 创建一个临时的 URL
          downloadUrl.value = URL.createObjectURL(blob);
        })
        .catch((error) => {
          console.error('获取图片数据失败:', error);
          ElMessageBox.alert('获取图片失败，请稍后重试', '提示', {
            confirmButtonText: '确定',
            type: 'error',
            customClass: 'center-message-box'
          });
        });
    console.log('后端返回的 imageUrl:', productForm.value.imageUrl);
  } else {
    ElMessageBox.alert(response.msg, '提示', {
      confirmButtonText: '确定',
      type: 'error',
      customClass: 'center-message-box'
    });
  }
};

const handleUploadError = () => {
  ElMessageBox.alert('图片上传失败，请稍后重试', '提示', {
    confirmButtonText: '确定',
    type: 'error',
    customClass: 'center-message-box'
  });
};

const beforeUpload = (file) => {
  const isJPG = file.type === 'image/jpeg' || file.type === 'image/png';
  const isLt5M = file.size / 1024 / 1024 < 5;
  
  if (!isJPG) {
    ElMessageBox.alert('只能上传 JPG/PNG 格式的图片', '提示', {
      confirmButtonText: '确定',
      type: 'error',
      customClass: 'center-message-box'
    });
    return false;
  }
  if (!isLt5M) {
    ElMessageBox.alert('上传图片大小不能超过 2MB!', '提示', {
      confirmButtonText: '确定',
      type: 'error',
      customClass: 'center-message-box'
    });
    return false;
  }
  return true;
};

// 修改商品函数
const editProduct = (product) => {
  // 设置表单数据
  productForm.value = {
    productId: product.productId,
    productName: product.productName,
    categoryId: product.categoryId,
    price: product.price,
    stock: product.stock,
    imageUrl: product.imageUrl,
    dict: product.dict
  };
  tempImageUrl.value = product.imageUrl;
  
  // 打开修改对话框
  dialogVisible1.value = true;
  
  // 确保已经获取类别列表
  if (!isCategoryListFetched.value && !isCategoryListFetchFailed.value) {
    fetchCategoryList();
  }
  
  // 确保已经获取单位列表
  if (!isDictListFetched.value && !isDictListFetchFailed.value) {
    fetchDictList();
  }
};

// 确认删除商品函数
const confirmDelete = async (productId) => {
  try {
    const result = await ElMessageBox.confirm(
      '确定要删除该商品吗？',
      '删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        customClass: 'center-message-box'
      }
    );
    
    if (result === 'confirm') {
      const response = await axiosInstance.delete(`/product/${productId}`);
      if (response.data.code === '200') {
        ElMessageBox.alert('商品删除成功', '提示', {
          confirmButtonText: '确定',
          type: 'success',
          customClass: 'center-message-box'
        });
        fetchProducts();
      } else {
        ElMessageBox.alert(response.data.message, '提示', {
          confirmButtonText: '确定',
          type: 'error',
          customClass: 'center-message-box'
        });
      }
    }
  } catch (error) {
    if (error === 'cancel') {
      return;
    }
    // 用户取消删除会进入catch，这里不需要处理
    if (error !== false) {
      console.error(error);
      ElMessageBox.alert('商品删除失败，请稍后重试', '提示', {
        confirmButtonText: '确定',
        type: 'error',
        customClass: 'center-message-box'
      });
    }
  }
};

// 修改saveProduct函数，使其同时支持添加和修改
const saveProduct = async () => {
  try {
    // 显式转换为数字类型，确保验证正常工作
    productForm.value.price = Number(productForm.value.price);
    productForm.value.stock = Number(productForm.value.stock);
    
    // 验证表单
    await productFormRef.value.validate();
    
    let response;
    if (productForm.value.productId) {
      // 修改商品
      response = await axiosInstance.post('/product/insert', productForm.value);
      if (response.data.code === '200') {
        ElMessageBox.alert('商品修改成功', '提示', {
          confirmButtonText: '确定',
          type: 'success',
          customClass: 'center-message-box'
        });
      }
    } else {
      // 添加商品
      response = await axiosInstance.post('/product/insert', productForm.value);
      if (response.data.code === '200') {
        ElMessageBox.alert('商品添加成功', '提示', {
          confirmButtonText: '确定',
          type: 'success',
          customClass: 'center-message-box'
        });
      }
    }
    
    if (response && response.data.code === '200') {
      cancelAdd();
      fetchProducts();
    } else if (response) {
      ElMessageBox.alert(response.data.message, '提示', {
        confirmButtonText: '确定',
        type: 'error',
        customClass: 'center-message-box'
      });
    }
  } catch (error) {
    if (error === false) {
      return;
    }
    console.error(error);
    ElMessageBox.alert('操作失败，请稍后重试', '提示', {
      confirmButtonText: '确定',
      type: 'error',
      customClass: 'center-message-box'
    });
  }
};

const handleCategoryChange = (categoryId) => {
  productForm.value.categoryId = categoryId;
};

const cancelAdd = () => {
  if (productFormRef.value) {
    productFormRef.value.resetFields();
  }
  dialogVisible.value = false;
  dialogVisible1.value = false;
  tempImageUrl.value = '';
};

const handleSizeChange = (newSize) => {
  pageSize.value = newSize;
  fetchProducts();
};

const handleCurrentChange = (newPage) => {
  currentPage.value = newPage;
  fetchProducts();
};

fetchProducts();
</script>

<style scoped>
/* 隐藏数字输入框的箭头 */
:deep(input[type="number"])::-webkit-outer-spin-button,
:deep(input[type="number"])::-webkit-inner-spin-button {
  -webkit-appearance: none !important;
  margin: 0;
}

:deep(input[type="number"]) {
  -moz-appearance: textfield !important;
}

/* 搜索区域样式 - 确保三个元素在一行显示 */
.flex {
  display: flex;
  flex-wrap: nowrap;
  align-items: center;
  gap: 16px;
  width: 100%;
}

.items-center {
  align-items: center;
}

.mb-4 {
  margin-bottom: 16px;
}

.flex-1 {
  flex: 1;
  min-width: 0;
}

.custom-input {
  width: 100%;
}

.mr-4 {
  margin-right: 16px;
}

/* 保留空行，确保文件格式正确 */
</style>